package com.pay;

import com.alipay.api.AlipayApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author cxt
 * @date 2021/11/20
 * 支付接口
 */
@Controller
@RequestMapping("/tool/pay")
@Slf4j
public class PayController {

    private PayService payService;

    // "支付宝支付接口"
    @PostMapping("/alipay")
    public void alipay(@RequestParam String registerId, @RequestParam boolean isAppoint, HttpServletResponse response) {
        try {
            payService.alipay(registerId, isAppoint, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // TODO 可以不写这个接口，个人认为作用不大
    // "支付验证"
    @PostMapping("/alipay/check")
    public boolean alipayCheck(@RequestParam String registerId) {
        return payService.alipayCheck(registerId);
    }

    /**
     * 支付宝异步付款结果通知
     */
    @PostMapping("/alipay/callback")
    public void alipayCallback(HttpServletRequest request) {
        try {
            payService.alipayCallback(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 支付宝退款
     * 注意：支付宝服务器发送的url是没有登录状态的，需要在系统中设置放过登录校验，不然接收不到通知
     */
    @PostMapping("/alipay/refund/callback")
    public boolean alipayRefundCallback(@RequestParam String outTradeNo, @RequestParam String tradeNo,
                                        @RequestParam String refundAmount, @RequestParam String subject) {
        boolean result = false;
        try {
            result = payService.alipayRefund(outTradeNo, tradeNo, refundAmount, subject);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return result;
    }

    // 退费查询
    @PostMapping("/alipay/refund/alipayRefundSelect")
    public boolean alipayRefundCallback(@RequestParam String outRequestNo, @RequestParam String tradeNo) {
        return payService.alipayRefundSelect(outRequestNo, tradeNo);
    }

    /**
     * 每天定时核对账单
     */
    @GetMapping("/check")
    @ResponseBody
    public void check() {
        try {
            // 1、获取对账文件：比如支付宝，拿着相应参数去请求当日对账文件，并解析对账文件，获得订单号、流水号、交易金额等信息
            payService.getBillDownload();
            // 2、数据处理：获取本地库当日数据，为减少数据库压力，只查询金额、订单号、流水号等主要信息


            // 3、数据核对处理：核对订单号与金额是否完全一致

            // 4、差异数据处理：核对不一样的数据，进行存入数据库

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
    }

    @Autowired
    public void setPayService(PayService payService) {
        this.payService = payService;
    }
}
